<template>
  <div class="comment-container">

    <!-- 新增：发表评论表单 -->
    <el-card class="add-comment-card">
      <h2 class="say-something">说点什么</h2>
      <el-form :model="commentForm" ref="commentFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="活动" prop="activityId">
              <el-select v-model="commentForm.activityId" placeholder="请选择活动" clearable>
                <el-option
                    v-for="activity in activityList"
                    :key="activity.id"
                    :label="activity.title"
                    :value="activity.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="新闻" prop="newsId">
              <el-select v-model="commentForm.newsId" placeholder="请选择新闻" clearable>
                <el-option
                    v-for="news in newsList"
                    :key="news.id"
                    :label="news.title"
                    :value="news.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="评论内容" prop="content">
          <el-input
              v-model="commentForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入评论内容"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitComment">发表评论</el-button>
          <el-button @click="resetCommentForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 评论列表 -->
    <el-card class="comment-list-card">
      <template #header>
        <div class="card-header">
          <h3 class="see-what">看看大家在说什么</h3>
          <!-- 将搜索栏整合到评论列表顶部 -->
          <el-form :model="searchForm" ref="searchFormRef" label-width="100px" class="search-form">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="活动" prop="activityId">
                  <el-select v-model="searchForm.activityId" placeholder="请选择活动" clearable>
                    <el-option
                        v-for="activity in activityList"
                        :key="activity.id"
                        :label="activity.title"
                        :value="activity.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="新闻" prop="newsId">
                  <el-select v-model="searchForm.newsId" placeholder="请选择新闻" clearable>
                    <el-option
                        v-for="news in newsList"
                        :key="news.id"
                        :label="news.title"
                        :value="news.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="时间范围" prop="timeRange">
                  <el-date-picker
                      v-model="searchForm.timeRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col v-for="comment in comments" :key="comment.id" :span="8">
          <el-card class="comment-item" shadow="hover">
            <div class="comment-info">
              <div class="comment-target">
                To <span class="commented-target">"{{ comment.commented }}"</span>
              </div>
              <div class="comment-content">
                {{ comment.content }}
              </div>
              <div class="comment-footer">
                <div class="user-info">
                  <div class="username-card">{{ comment.userName }}</div>
                  <span class="update-time">{{ formatDateTime(comment.updatedAt) }}</span>
                </div>
                <div class="like-info">
                  <el-button
                      type="text"
                      class="like-button"
                      @click="handleLike(comment)"
                  >
                    <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" class="like-icon">
                      <path d="M885.9 533.7c16.8-22.2 26.1-49.4 26.1-77.7 0-44.9-25.1-87.4-65.5-111.1a67.67 67.67 0 0 0-34.3-9.3H572.4l6-122.9c1.4-29.7-9.1-57.9-29.5-79.4-20.5-21.5-48.1-33.4-77.9-33.4-52 0-98 35-111.8 85.1l-85.9 311h-.3v428h472.3c9.2 0 18.2-1.8 26.5-5.4 47.6-20.3 78.3-66.8 78.3-118.4 0-12.6-1.8-25-5.4-37 16.8-22.2 26.1-49.4 26.1-77.7 0-12.6-1.8-25-5.4-37 16.8-22.2 26.1-49.4 26.1-77.7-.2-12.6-2-25.1-5.6-37.1zM112 528v364c0 17.7 14.3 32 32 32h65V496h-65c-17.7 0-32 14.3-32 32z"/>
                    </svg>
                    <span class="like-count">{{ comment.likeCount || 0 }}</span>
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[8, 16, 24, 32]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/axios'  // 修正导入路径
import dayjs from 'dayjs'
import { ThumbsUp } from '@element-plus/icons-vue'

const comments = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(8)

// 搜索表单
const searchForm = reactive({
  activityId: null,
  newsId: null,
  timeRange: []
})

const activityList = ref([])
const newsList = ref([])

// 新增：评论表单
const commentForm = reactive({
  activityId: null,
  newsId: null,
  content: ''
})

// 获取评论列表
const loadComments = async () => {
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      activityId: searchForm.activityId,
      newsId: searchForm.newsId
    }

    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.startTime = searchForm.timeRange[0]
      params.endTime = searchForm.timeRange[1]
    }

    const res = await axios.get('/comment/loadDataList', { params })

    if (res.status === 'success') {
      comments.value = res.data.list.map(comment => ({
        id: comment.id,
        content: comment.content,
        userName: comment.userName,
        commented: comment.commented,
        likeCount: comment.likeCount || 0,
        updatedAt: comment.updatedAt
      }))
      total.value = res.data.totalCount
      currentPage.value = res.data.pageNo
      pageSize.value = res.data.pageSize
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  }
}

// 格式化时间
const formatDateTime = (datetime) => {
  return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadComments()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadComments()
}

// 删除评论

// 新增：提交评论
const submitComment = async () => {
  if (!commentForm.activityId && !commentForm.newsId) {
    ElMessage.error('请选择活动或新闻')
    return
  }
  if (!commentForm.content) {
    ElMessage.error('请输入评论内容')
    return
  }

  try {
    const res = await axios.post('/comment/add', {
      activityId: commentForm.activityId,
      newsId: commentForm.newsId,
      content: commentForm.content,
      userId: localStorage.getItem('userId') // 添加用户ID
    })

    if (res.status === 'success') {
      resetCommentForm()
      loadComments()
    } else {
      ElMessage.error(res.info || '评论发表失败')
    }
  } catch (error) {
    console.error('评论发表失败:', error)
    ElMessage.error('评论发表失败')
  }
}

// 新增：重置评论表单
const resetCommentForm = () => {
  commentForm.activityId = null
  commentForm.newsId = null
  commentForm.content = ''
}

// 搜索
const handleSearch = () => {
  if (searchForm.activityId && searchForm.newsId) {
    ElMessage.error('请只选择活动或新闻中的一个进行搜索')
    return
  }
  currentPage.value = 1
  loadComments()
}

// 重置搜索
const resetSearch = () => {
  searchForm.activityId = null
  searchForm.newsId = null
  searchForm.timeRange = []
  currentPage.value = 1
  loadComments()
}

// 加载活动列表
const loadActivities = async () => {
  try {
    const res = await axios.get('/activity/loadDataList', {
      params: {
        pageNo: 1,
        pageSize: 1000, // 获取所有活动
        orderBy: 'created_at desc'
      }
    })

    if (res.status === 'success') {
      activityList.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  }
}

// 加载新闻列表
const loadNews = async () => {
  try {
    const res = await axios.get('/news/loadDataList', {
      params: {
        pageNo: 1,
        pageSize: 1000, // 获取所有新闻
        orderBy: 'created_at desc'
      }
    })

    if (res.status === 'success') {
      newsList.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  }
}

// 点赞处理
const handleLike = async (comment) => {
  try {
    const res = await axios.post('/comment/addLikeCount', {
      id: comment.id
    })

    if (res.status === 'success') {
      // 直接使用后端返回的点赞数更新界面
      comment.likeCount = res.data
    } else {
      ElMessage.error(res.info || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 初始加载
onMounted(() => {
  loadComments()
  loadActivities()
  loadNews()
})
</script>

<style scoped>
.comment-container {
  padding: 20px;
}

.say-something {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.see-what {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.add-comment-card {
  margin-bottom: 20px;
}

.comment-list-card {
  min-height: 400px;
}

.comment-item {
  margin-bottom: 15px;
  height: auto;
  transition: all 0.3s ease;
  border: none;
  padding: 15px;
}

.comment-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.comment-info {
  position: relative;
}

.comment-target {
  font-size: 14px;
  color: #8c8c8c;
  margin-bottom: 8px;
  font-weight: normal;
}

.commented-target {
  color: #67c23a;
  font-weight: 500;
}

.comment-content {
  position: relative;
  padding: 12px 15px;
  background: #ecf5ff;
  border-radius: 8px;
  margin-bottom: 15px;
  color: #2c3e50;
  line-height: 1.5;
  font-size: 14px;
}

.comment-content::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 20px;
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid #ecf5ff;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 0;
  margin-top: 5px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 0;
}

.username-card {
  background: #ecf5ff;
  padding: 4px 10px;
  border-radius: 10px;
  font-size: 14px;
  color: #409EFF;
  font-weight: 500;
  transition: all 0.3s ease;
}

.username-card:hover {
  background: #409EFF;
  color: #fff;
}

.update-time {
  font-size: 11px;
  color: #909399;
}

.like-info {
  margin-right: 10px;
}

.like-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 20px;
  transition: all 0.3s ease;
  height: auto;
  background: #fff;
  border: 1px solid #e4e7ed;
}

.like-button:hover {
  background-color: #ecf5ff;
  color: #409EFF;
  border-color: #409EFF;
}

.like-icon {
  width: 16px;
  height: 16px;
  fill: currentColor;
}

.like-count {
  font-size: 14px;
  font-weight: 500;
  margin-left: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.search-form {
  margin-top: 10px;
}
</style>